package com.tramp.frame.server.thread;

import com.tramp.basic.service.OperateLogService;
import com.tramp.frame.config.BaseConfig;
import com.tramp.frame.server.pageplugin.PageInfoHolder;
import com.tramp.utils.SpringContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tramp.frame.server.exception.GenericException;

import javax.servlet.http.HttpServletRequest;

/**
 * 线程初始化总控制中心
 */
public final class ThreadInitCenter {

	private static final Logger LOGGER = LoggerFactory.getLogger(ThreadInitCenter.class);

	private static PageInfoHolder pageInfoHolder;

	private static OperateLogService operateLogService;

	private static BaseConfig baseConfig;

	private ThreadInitCenter() {

	}

	public static void init(HttpServletRequest request) {
		if (null == baseConfig) {
			baseConfig = SpringContextHolder.getBean(BaseConfig.class);
		}
		String pageStart = request.getParameter(baseConfig.getStart());
		String pageLimit = request.getParameter(baseConfig.getLimit());
		String operateUrl = request.getRequestURI();
		//线程缓存初始化
		ThreadCacheStore.init();

		//操作日志初始化
		if (null == operateLogService) {
			operateLogService = SpringContextHolder.getBean(OperateLogService.class);
		}
		if (null != operateLogService) {
			operateLogService.init();
			//记录Url访问日志
			operateLogService.addOperateLogAction(operateUrl, null);
		}
		else {
			LOGGER.warn("ThreadInitCenter fail,operateLogService is null.The system may also be initialized!");
		}

		//分页信息初始化
		if (null == pageInfoHolder) {
			pageInfoHolder = SpringContextHolder.getBean(PageInfoHolder.class);
		}
		if (null != pageInfoHolder) {
			if (StringUtils.isNotBlank(pageStart) && StringUtils.isNotBlank(pageLimit)) {
				try {
					pageInfoHolder.setPageInfoModel(Integer.valueOf(pageStart), Integer.valueOf(pageLimit));
				}
				catch (Exception ex) {
					throw new GenericException("获取分页信息出现异常");
				}
			}
		}
		else {
			LOGGER.warn("ThreadInitCenter fail,pageInfoHolder is null.The system may also be initialized!");
		}
	}

	public static void end() {
		//提交操作记录至待插入数据的队列中
		operateLogService.commitToBlockingQueue();
		//线程缓存初始化
		ThreadCacheStore.destory();
	}

}
